//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.example.mall.controller;

import com.example.mall.common.api.CommonPage;
import com.example.mall.common.api.CommonResult;
import com.example.mall.dto.UserDto;
import com.example.mall.mbg.model.Role;
import com.example.mall.mbg.model.User;
import com.example.mall.service.RoleService;
import com.example.mall.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = {"UserController"},description = "用户管理")
@Controller
@RequestMapping({"/user"})
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    public UserController() {
    }

    @RequestMapping(value = {"error"},method = {RequestMethod.GET})
    public String error(Model model) {
        return "error-500";
    }

    @ApiOperation("画面：登录")
    @RequestMapping(value = {"login"},method = {RequestMethod.GET})
    public String login(Model model) {
        return "auth-login";
    }

    @ApiOperation("注册")
    @RequestMapping(value = {"/create"}, method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult createUser(@RequestBody User user) {
        user.setUserid(userService.getNextId());
        user.setRoleid(2);
        user.setCreatetime(new Date());
        user.setUpdatetime(user.getCreatetime());
        int count = this.userService.create(user);
        CommonResult commonResult;
        if (count == 1) {
            commonResult = CommonResult.success(user);
            LOGGER.debug("createUser success:{}", user);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("createUser failed:{}", user);
        }

        return commonResult;
    }

    @ApiOperation("画面：注册")
    @RequestMapping(value = {"register"},method = {RequestMethod.GET})
    public String register(Model model) {
        return "auth-register";
    }

    @ApiOperation("画面：忘记密码")
    @RequestMapping(value = {"forgotpw"},method = {RequestMethod.GET})
    public String forgotpw(Model model) {
        return "auth-forgotpw";
    }

    @ApiOperation("画面：退出登录")
    @RequestMapping(value = {"logout"},method = {RequestMethod.GET})
    public String logout(Model model) {
        return "auth-logout";
    }

    @ApiOperation("画面：用户列表")
    @RequestMapping(value = {"init"},method = {RequestMethod.GET})
    public String init(Model model, HttpSession session) {
        List<UserDto> userDtos = new ArrayList();
        List<User> users = this.userService.listAll();
        users.forEach((user) -> {
            UserDto userDto = new UserDto(user);
            Role role = this.roleService.get(user.getRoleid());
            userDto.setRole(role);
            userDtos.add(userDto);
        });
        model.addAttribute("userDtos", userDtos);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "user-list";
    }

    @ApiOperation("获取所有用户列表")
    @RequestMapping(value = {"listAll"}, method = {RequestMethod.GET})
    @ResponseBody
    public CommonResult<List<UserDto>> getUserList() {
        List<UserDto> userDtos = new ArrayList();
        List<User> users = this.userService.listAll();
        users.forEach((user) -> {
            UserDto userDto = new UserDto(user);
            Role role = this.roleService.get(user.getRoleid());
            userDto.setRole(role);
            userDtos.add(userDto);
        });
        return CommonResult.success(userDtos);
    }

    @ApiOperation("账号密码验证")
    @RequestMapping(value = {"/loginverify"}, method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult loginVerify(@RequestBody User user, HttpSession session) {
        User userverify = this.userService.getUserByUsernamePassword(user);
        CommonResult commonResult;
        if (userverify != null) {
            session.setAttribute("user", userverify);
            commonResult = CommonResult.success(user);
            LOGGER.debug("createUser success:{}", user);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("createUser failed:{}", user);
        }
        return commonResult;
    }

    @ApiOperation("画面：用户编辑")
    @RequestMapping(value = {"edit"},method = {RequestMethod.GET})
    public String edit(Model model, Integer userid, HttpSession session) {
        User user = userService.get(userid);
        List<Role> roleList = roleService.listAll();
        model.addAttribute("user", user);
        model.addAttribute("roleList", roleList);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "user-detail";
    }

    @ApiOperation("画面：用户编辑")
    @RequestMapping(value = {"selfinfo"},method = {RequestMethod.GET})
    public String selfinfo(Model model, HttpSession session) {
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        List<Role> roleList = roleService.listAll();
        model.addAttribute("roleList", roleList);
        return "self-info";
    }

    @ApiOperation("更新指定id用户信息")
    @RequestMapping(value = {"/update/{id}"}, method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult updateUser(@PathVariable("id") Integer userid, @RequestBody User user, BindingResult bindingResult) {
        int count = this.userService.update(userid, user);
        CommonResult commonResult;
        if (count == 1) {
            commonResult = CommonResult.success(user);
            LOGGER.debug("updateUser success:{}", user);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("updateUser failed:{}", user);
        }

        return commonResult;
    }

    @ApiOperation("删除指定id的用户")
    @RequestMapping(value = {"/delete/{id}"}, method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult deleteUser(@PathVariable("id") Integer userid) {
        int count = this.userService.delete(userid);
        CommonResult commonResult;
        if (count == 1) {
            commonResult = CommonResult.success((Object)null);
            LOGGER.debug("deleteUser success:id={}", userid);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("deleteUser failed:id={}", userid);
        }
        return commonResult;
    }

    @ApiOperation("分页查询用户列表")
    @RequestMapping(
            value = {"/list"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public CommonResult<CommonPage<UserDto>> listUser(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize) {
        List<UserDto> userDtos = new ArrayList();
        List<User> userList = this.userService.list(pageNum, pageSize);
        userList.forEach((user) -> {
            UserDto userDto = new UserDto(user);
            Role role = this.roleService.get(user.getRoleid());
            userDto.setRole(role);
            userDtos.add(userDto);
        });
        return CommonResult.success(CommonPage.restPage(userDtos));
    }

    @ApiOperation("获取指定id的用户详情")
    @RequestMapping(
            value = {"/{id}"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public CommonResult<UserDto> user(@PathVariable("id") Integer userid) {
        User user = this.userService.get(userid);
        UserDto userDto = new UserDto(user);
        Role role = this.roleService.get(user.getRoleid());
        userDto.setRole(role);
        return CommonResult.success(userDto);
    }
}
